using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.WorkOrderTask;
using WPF_MVVM_Test.MVVM_ViewModel;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_View.WorkOrderTask
{
    /// <summary>
    /// DispatchDialog.xaml 的交互逻辑
    /// </summary>
    public partial class DispatchDialog : Window, INotifyPropertyChanged
    {
        #region 私有字段

        private readonly WorkOrderTaskApiService _apiService;
        private readonly List<WorkOrderTaskModel> _selectedTasks;
        private string _selectedTeam;
        private string _selectedSupervisor;
        private string _selectedQualityDepartment;
        private string _selectedQualityPersonnel;
        private string _otherMembers;
        private string _notes;

        #endregion

        #region 构造函数

        public DispatchDialog(List<WorkOrderTaskModel> selectedTasks)
        {
            InitializeComponent();
            _apiService = new WorkOrderTaskApiService();
            _selectedTasks = selectedTasks;

            DataContext = this;
            InitializeData();
            InitializeCommands();
        }

        #endregion

        #region 属性

        /// <summary>
        /// 选中的任务列表
        /// </summary>
        public ObservableCollection<WorkOrderTaskModel> SelectedTasks { get; set; }

        /// <summary>
        /// 班组选项
        /// </summary>
        public ObservableCollection<string> TeamOptions { get; set; }

        /// <summary>
        /// 负责人选项
        /// </summary>
        public ObservableCollection<string> SupervisorOptions { get; set; }

        /// <summary>
        /// 质量部门选项
        /// </summary>
        public ObservableCollection<string> QualityDepartmentOptions { get; set; }

        /// <summary>
        /// 质量人员选项
        /// </summary>
        public ObservableCollection<string> QualityPersonnelOptions { get; set; }

        /// <summary>
        /// 选中的班组
        /// </summary>
        public string SelectedTeam
        {
            get => _selectedTeam;
            set => SetProperty(ref _selectedTeam, value);
        }

        /// <summary>
        /// 选中的负责人
        /// </summary>
        public string SelectedSupervisor
        {
            get => _selectedSupervisor;
            set => SetProperty(ref _selectedSupervisor, value);
        }

        /// <summary>
        /// 选中的质量部门
        /// </summary>
        public string SelectedQualityDepartment
        {
            get => _selectedQualityDepartment;
            set => SetProperty(ref _selectedQualityDepartment, value);
        }

        /// <summary>
        /// 选中的质量人员
        /// </summary>
        public string SelectedQualityPersonnel
        {
            get => _selectedQualityPersonnel;
            set => SetProperty(ref _selectedQualityPersonnel, value);
        }

        /// <summary>
        /// 其他成员
        /// </summary>
        public string OtherMembers
        {
            get => _otherMembers;
            set => SetProperty(ref _otherMembers, value);
        }

        /// <summary>
        /// 备注
        /// </summary>
        public string Notes
        {
            get => _notes;
            set => SetProperty(ref _notes, value);
        }

        /// <summary>
        /// 摘要文本
        /// </summary>
        public string SummaryText => $"将对 {SelectedTasks?.Count ?? 0} 个任务进行批量派工";

        #endregion

        #region 命令

        public ICommand ConfirmCommand { get; private set; }
        public ICommand CancelCommand { get; private set; }
        public ICommand SelectMembersCommand { get; private set; }

        #endregion

        #region 私有方法

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitializeData()
        {
            SelectedTasks = new ObservableCollection<WorkOrderTaskModel>(_selectedTasks);

            // 调试信息：显示接收到的任务
            var taskInfo = string.Join("\n", _selectedTasks.Select(t => $"ID: {t.Id}, 任务名称: {t.TaskName}, 状态: {t.Status}"));
            System.Diagnostics.Debug.WriteLine($"派工对话框接收到的任务数量: {_selectedTasks.Count}");
            System.Diagnostics.Debug.WriteLine($"派工对话框接收到的任务详情:\n{taskInfo}");

            // 初始化选项数据（实际项目中应该从API获取）
            TeamOptions = new ObservableCollection<string>
            {
                "A班", "B班", "C班", "D班"
            };

            SupervisorOptions = new ObservableCollection<string>
            {
                "张三", "李四", "王五", "赵六"
            };

            QualityDepartmentOptions = new ObservableCollection<string>
            {
                "质量部", "检验科", "品控部"
            };

            QualityPersonnelOptions = new ObservableCollection<string>
            {
                "质检员A", "质检员B", "质检员C"
            };
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void InitializeCommands()
        {
            ConfirmCommand = new RelayCommand(async () => await ConfirmDispatchAsync(), CanConfirm);
            CancelCommand = new RelayCommand(() => DialogResult = false);
            SelectMembersCommand = new RelayCommand(SelectMembers);
        }

        /// <summary>
        /// 是否可以确认派工
        /// </summary>
        private bool CanConfirm()
        {
            return !string.IsNullOrWhiteSpace(SelectedTeam) &&
                   !string.IsNullOrWhiteSpace(SelectedSupervisor);
        }

        /// <summary>
        /// 确认派工
        /// </summary>
        private async Task ConfirmDispatchAsync()
        {
            try
            {
                var teamName = SelectedTeam ?? "";
                var supervisor = SelectedSupervisor ?? "";
                var qualityDepartment = SelectedQualityDepartment ?? "";
                var qualityPersonnel = SelectedQualityPersonnel ?? "";
                var otherMembers = OtherMembers ?? "";
                var notes = Notes ?? "";

                int successCount = 0;
                int totalCount = SelectedTasks.Count;

                // 循环调用单个派工接口
                foreach (var task in SelectedTasks)
                {
                    var success = await _apiService.DispatchAsync(
                        task.Id, teamName, supervisor, qualityDepartment,
                        qualityPersonnel, otherMembers, notes);

                    if (success)
                    {
                        successCount++;
                    }
                }

                if (successCount == totalCount)
                {
                    MessageBox.Show($"成功派工 {successCount} 个任务！", "成功",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    DialogResult = true;
                }
                else if (successCount > 0)
                {
                    MessageBox.Show($"部分派工成功：{successCount}/{totalCount} 个任务派工成功！", "部分成功",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
                    DialogResult = true;
                }
                else
                {
                    MessageBox.Show("派工失败，请重试！", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"派工失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 选择成员
        /// </summary>
        private void SelectMembers()
        {
            // 这里可以打开人员选择对话框
            // 暂时使用简单的输入框
            MessageBox.Show("人员选择功能待实现", "提示",
                MessageBoxButton.OK, MessageBoxImage.Information);
        }

        #endregion

        #region INotifyPropertyChanged实现

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion
    }
}
